package com.java1234.jxc.controller.admin;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.java1234.jxc.beans.*;
import com.java1234.jxc.core.page.Pagination;
import com.java1234.jxc.service.LogService;
import com.java1234.jxc.service.MenuService;
import com.java1234.jxc.service.RoleService;
import com.java1234.jxc.service.UserService;
import com.java1234.jxc.utils.StringUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/admin/role")
public class RoleAdminController {
    @Autowired
    RoleService roleService;
    @Autowired
    UserService userService;
    @Autowired
    MenuService menuService;
    @Autowired
    LogService logService;

    @Autowired
    Dao dao;

    @ResponseBody
    @RequestMapping("/saveMenuSet")
    public Map<String,Object> saveMenuSet(String  menuIds,Integer roleId) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        if (StringUtil.isNotEmpty(menuIds)&&roleId!=null) {
            List<String> menuList = Arrays.asList(menuIds.split(","));
            // 清除角色与menu 的关联关系
            dao.clear(SysRoleMenu.class,Cnd.where("role_id","=",roleId));
            menuList.forEach(item->{
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(Integer.parseInt(item));
                dao.insert(roleMenu);
            });

            resultMap.put("success",true);
            // 设置角色与menu的关联关系

        }else{
            dao.clear(SysRoleMenu.class,Cnd.where("role_id","=",roleId));
            resultMap.put("success",true);
        }
        logService.insert(new SysLog(SysLog.ADD_ACTION,"saveMenuSet"));

        return resultMap;

    }



    /**
     * 根据父节点获取所有复选框权限菜单
     * @param parentId
     * @param roleId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/loadCheckMenuInfo")
    public String loadCheckMenuInfo(Integer parentId,Integer roleId) throws Exception{
        SysRole sysRole = dao.fetchLinks(roleService.fetch(roleId), "menus");
        List<SysMenu> menuList = sysRole.getMenus();
        List<Integer> menuIdList = new ArrayList<>();
        for (SysMenu menu : menuList) {
            menuIdList.add(menu.getId());
        }
        return getAllCheckMenuByParentId(parentId,menuIdList).toString();
    }

    /**
     * 根据父节点id和权限菜单id获取所有复选框菜单集合
     * @param parentId
     * @param menuIdList
     * @return
     */
    public JsonArray getAllCheckMenuByParentId(Integer parentId,List<Integer> menuIdList){
        JsonArray jsonArray = this.getCheckMenuByParentId(parentId,menuIdList);
        for (int i =0;i<jsonArray.size();i++){
            JsonObject jsonObject = (JsonObject)jsonArray.get(i);
            if("open".equals(jsonObject.get("state").getAsString())){
                continue;
            }else{
                jsonObject.add("children", getAllCheckMenuByParentId(jsonObject.get("id").getAsInt(), menuIdList));
            }
        }
        return jsonArray;

    }

    /**
     * 根据父节点id 和权限菜单集合获取一层复选框菜单集合
     * @param parentId
     * @param menuIdList
     * @return
     */
    public JsonArray getCheckMenuByParentId(Integer parentId,List<Integer> menuIdList){
        List<SysMenu> menuList = menuService.query(Cnd.where("pid","=",parentId));
        JsonArray jsonArray = new JsonArray();
        for (SysMenu menu: menuList){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id",menu.getId());
            jsonObject.addProperty("text",menu.getName());
            if (menu.getState()==1){
                jsonObject.addProperty("state","closed"); // 根节点
            }else{
                jsonObject.addProperty("state","open"); // 叶子节点
            }
            jsonObject.addProperty("iconCls",menu.getIcon()); // 节点图标
            if (menuIdList.contains(menu.getId())){
                jsonObject.addProperty("checked",true);
            }
            jsonArray.add(jsonObject);
        }

        return jsonArray;
    }


    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(SysRole role) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        // 删除角色的同时,删除角色与用户,与权限的关系
        logService.insert(new SysLog(SysLog.DELETE_ACTION,roleService.fetch(role.getId()).toString()));
        roleService.delete(role.getId());

        dao.clear(SysUserRole.class,Cnd.where("role_id","=",role.getId()));
        dao.clear(SysRoleMenu.class,Cnd.where("role_id","=",role.getId()));
        resultMap.put("success",true);

        return resultMap;
    }


    @RequestMapping("/save")
    @ResponseBody
    public Map<String,Object> save(SysRole role) throws Exception{
        Map<String, Object> resultMap = new HashMap<>();

        // 两种情况判断有没有ID
        if(role.getId()==null){
            int count = roleService.count(Cnd.where("name", "=", role.getName()));
            if (count>0){
                resultMap.put("success",false);
                resultMap.put("errorInfo","角色名称已经存在!");
                return resultMap;
            }
            SysRole insert = roleService.insert(role);
            logService.insert(new SysLog(SysLog.ADD_ACTION,insert.toString()));

        }else{

            SysRole fetch = roleService.fetch(role.getId());
            System.out.println(fetch.getName());
            if (!fetch.getName().equals(role.getName())){
                int count = roleService.count(Cnd.where("name", "=", role.getName()));
                if (count>0){
                    resultMap.put("success",false);
                    resultMap.put("errorInfo","角色名称已经存在!");
                    return resultMap;
                }
            }
              roleService.updateIgnoreNull(role);
            logService.insert(new SysLog(SysLog.UPDATE_ACTION,role.getId()+""));

        }

        resultMap.put("success",true);
        return resultMap;




    }

    @RequestMapping("/listAll")
    @ResponseBody
    public Map<String,Object> listAll(){
        Map<String,Object> resultMap = new HashMap<>();
        List<SysRole> list = roleService.query();

        resultMap.put("rows",list);
        return resultMap;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String,Object> list(SysRole role,
                                   @RequestParam(value = "page",required = false)Integer page,
                                   @RequestParam(value = "rows",required = false)Integer rows) {
        Map<String, Object> resultMap = new HashMap<>();
        Cnd cnd = Cnd.where("id", "!=", 1);
        if (role!=null&&role.getName()!=null){
            cnd.and("name","like","%"+role.getName()+"%");
        }
        cnd.asc("id");

        Pagination pagination = roleService.listPage(page, rows, cnd);
        List<SysRole> list = (List<SysRole>) pagination.getList();

       list.forEach(item->{
            dao.fetchLinks(item,"^menus$");
       });

       for (SysRole sysRole: list){
           StringBuffer sb = new StringBuffer();
           List<SysMenu> menus = sysRole.getMenus();
            for (SysMenu menu:menus){
                sb.append(","+menu.getName());
            }
            sysRole.setMenuList(sb.toString().replaceFirst(",",""));

       }
       resultMap.put("rows",list);
       resultMap.put("total",pagination.getTotalCount());
       logService.insert(new SysLog(SysLog.SEARCH_ACTION,"角色列表查询"));
       return resultMap;
    }


}
